package cash.cmp.personal_financial_system.controller;

import cash.cmp.personal_financial_system.model.*;
import cash.cmp.personal_financial_system.model.account.Account;
import cash.cmp.personal_financial_system.service.impl.AccountServiceImpl;
import cash.cmp.personal_financial_system.service.impl.BillServiceImpl;
import cash.cmp.personal_financial_system.service.impl.RoleServiceImpl;
import cash.cmp.personal_financial_system.service.impl.UserServiceImpl;
import cash.cmp.personal_financial_system.utils.QiniuUtils;
import cash.cmp.personal_financial_system.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private AccountServiceImpl accountService;
    @Autowired
    private BillServiceImpl billService;
    @Autowired
    private RoleServiceImpl roleService;

    @RequestMapping(value="/getById")
    public Result findUserById() {
        Account account = (Account) SecurityUtils.getSubject().getPrincipal();
        User user = userService.findUserById(account.getId());
        return Result.succ(200,"success",user);
    }

    @RequiresRoles(value = "admin")
    @RequestMapping(value = "/findAllUser")
    public Result findAllUser() {
        List<User> users = userService.findAllUser();
        return Result.succ(200,"success",users);
    }
//    @RequiresRoles(value = "admin")
    @RequestMapping(value = "/findByAll")
    public Result findByAll(@RequestBody Map<String,String> data) {
        Integer id = null;
        if ( data.get("id") != null){
            id = Integer.parseInt(data.get("id"));
        }
        Integer sex = null;
        if( data.get("sex") != null ) {
            sex = Integer.parseInt(data.get("sex"));
        }
        String city = data.get("city");
        String tel = data.get("tel");
        int page = Integer.parseInt(data.get("page"));

        Page<User> pageObject = new Page<>();
        if(data.get("pageSize") != null) {
            pageObject.setPageSize(Integer.parseInt(data.get("pageSize")));
        }
        int count = userService.countByAll(id,tel,sex,city);
        pageObject.setPage(page);
        pageObject.setTotal(count);
        List<User> users = userService.findByAll(id,tel,sex,city,page, pageObject.getPageSize());
        pageObject.setData(users);
        return Result.succ(200,"success",pageObject);
    }

    @RequestMapping(value = "/findByLike")
    public Result findByLike(@RequestBody Map<String,String> data){
        String like = data.get("like");
        List<User> users = userService.findByLike(like);
        return Result.succ(200,"success",users);
    }

    @RequiresRoles(value = "admin")
    @RequestMapping(value = "/findAllByPage")
    public Result findAllByPage(@RequestBody Map<String,Integer> data) {
        int page = data.get("page");
        Page<User> pageObject = new Page<>();
        if(data.get("pageSize") != null) {
            pageObject.setPageSize(data.get("pageSize"));
        }

        int count = userService.countUser();
        pageObject.setPage(page);
        pageObject.setTotal(count);
        List<User> users = userService.findAllByPage(page, pageObject.getPageSize());
        pageObject.setData(users);

        return Result.succ(200,"success",pageObject);
    }

    // 注销用户接口, 前端传入用户的 id；’id‘
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/deleteUser")
    public Result deleteUser(@RequestBody Map<String, String> data) {
        int id = Integer.parseInt(data.get("id"));
        boolean flag1 = userService.deleteUser(id);
        if (billService.findBill(id) != null){
            billService.deleteBillById(id);
        }
        boolean flag2 = roleService.deleteUserRole(id);
        boolean flag3 = accountService.deleteAccount(id);
        System.out.println("flag1" + flag1 + ",flag2" + flag2 + ",flag3" + flag3 );
        if(flag1 && flag2 && flag3) {
            return Result.succ(200,"success",null);
        }
        return Result.fail("注销失败");
    }

    @RequestMapping(value = "/updateUser")
    public Result updateUser(@RequestBody User user){
        Boolean flag = userService.updateUser(user);
        if(!flag) {
            return Result.fail("修改失败");
        }
        return  Result.succ(200,"success",null);
    }

    // 获取用户角色名，可能多个
    @RequestMapping(value = "/getUserRolesById")
    public Result getUserRolesById(){
        Account account = (Account) SecurityUtils.getSubject().getPrincipal();
        List<Role> roles = userService.getUserRolesById(account.getId());
        return  Result.succ(200,"success",roles);
    }

    // 用户修改图片
    @RequestMapping(value = "/updateImage")
    public Result updateImage(@RequestParam("file") MultipartFile file) throws IOException {
        Account account = (Account) SecurityUtils.getSubject().getPrincipal();
        User user = userService.findUserById(account.getId());
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");

        if(!user.getHeadImage().equals("image_default.png")) {
            QiniuUtils.deleteFileFromQiniu(user.getHeadImage());
        }

        String imageName = user.getId() + "," +ft.format(user.getRegister());
        Boolean flag = userService.updateImage(imageName, account.getId());

        if(flag){
            QiniuUtils.upload2Qiniu(file.getBytes(),imageName);
            return  Result.succ(200,"success",imageName);
        }
        return Result.fail("持久化user表错误");
    }

    // 用户根据图片名获取图片
    @RequestMapping(value = "/getImage")
    public Result updateImage() throws UnsupportedEncodingException {
        Account account = (Account) SecurityUtils.getSubject().getPrincipal();
        User user = userService.findUserById(account.getId());
        String imageName = user.getHeadImage();
        String finalUrl = QiniuUtils.getEAndToken(imageName);
        return  Result.succ(200,"success",finalUrl);
    }

}
